package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

@Service
@Slf4j
public class BlockingQueuePrintABCService {

    private static final int TOTAL_CYCLES = 5; // 总共循环5次AAABBC
    private final BlockingQueue<Integer> queueA = new ArrayBlockingQueue<>(1);
    private final BlockingQueue<Integer> queueB = new ArrayBlockingQueue<>(1);
    private final BlockingQueue<Integer> queueC = new ArrayBlockingQueue<>(1);

    public void printABCSequence() {
        Thread threadA = new Thread(this::printA);
        Thread threadB = new Thread(this::printB);
        Thread threadC = new Thread(this::printC);

        threadA.start();
        threadB.start();
        threadC.start();

        try {
            // 开始时先让线程A启动
            queueA.put(1);

            threadA.join();
            threadB.join();
            threadC.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("主线程被中断", e);
        }

        log.info("所有循环已完成，任务结束");
    }

    private void printA() {
        try {
            for (int cycle = 0; cycle < TOTAL_CYCLES; cycle++) {
                for (int i = 0; i < 3; i++) {  // 打印3次A
                    queueA.take();  // 等待从队列中获取任务信号
                    log.info("A");
                    if (i == 2) {  // 完成3次A的打印后唤醒线程B
                        queueB.put(1);
                    } else {
                        queueA.put(1);  // 继续打印A
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("线程A被中断", e);
        }
    }

    private void printB() {
        try {
            for (int cycle = 0; cycle < TOTAL_CYCLES; cycle++) {
                for (int i = 0; i < 2; i++) {  // 打印2次B
                    queueB.take();  // 等待从队列中获取任务信号
                    log.info("B");
                    if (i == 1) {  // 完成2次B的打印后唤醒线程C
                        queueC.put(1);
                    } else {
                        queueB.put(1);  // 继续打印B
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("线程B被中断", e);
        }
    }

    private void printC() {
        try {
            for (int cycle = 0; cycle < TOTAL_CYCLES; cycle++) {
                queueC.take();  // 等待从队列中获取任务信号
                log.info("C");
                queueA.put(1);  // 完成打印C后，唤醒线程A开始下一个循环
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("线程C被中断", e);
        }
    }
}
